package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    //配置中写好的服务器保存图片的地址
    @Value("${reggie.path}")
    private String basePath;


    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //file就是上传来的源文件

        String originalFilename = file.getOriginalFilename();

        //防止名字重复 的操作

        int lastIndexOf = originalFilename.lastIndexOf(".");

        //拿到  . 后面的后缀名后拼接一个随机的字符串作为名字
        String fileSuff = originalFilename.substring(lastIndexOf);

        //    32位+4个-的随机字符串(永不重复)
        String fileName = UUID.randomUUID().toString() + fileSuff;


        //检测服务器用于保存的文件夹是否存在，不存在则创建
        File dir = new File(basePath);

        if (!dir.exists()){
            dir.mkdirs();
        }

        File uploadFile = new File(basePath,fileName);

        try {
            file.transferTo(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("程序上传过程中遇到问题，请稍后重试");
        }

        return R.success(fileName);
    }

    /**
     * 下载（预览图片）
     * 写void  不返回R对象   通过字节输出流  把数据响应到浏览器
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){


        try {
            File srcFile = new File(basePath,name);
            //读到服务器内存中
            FileInputStream in = new FileInputStream(srcFile);

            //从服务器内存到浏览器的输出流
            ServletOutputStream out = response.getOutputStream();

            //写入
            int len = 0;
            byte[] buffer = new byte[8*1024];

            while ((len = in.read(buffer)) !=-1){
                //读多少   写多少
                out.write(buffer,0,len);
            }
//            out.close(); response对象会关联
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
